package com.akk.task;


import com.akk.module.yb.model.TradeInfoQueryResponse;
import com.akk.module.yb.service.YbService;
import com.akk.utils.RestResponse;
import com.akk.utils.exception.BusinessException;
import com.google.gson.Gson;
import org.apache.commons.httpclient.HttpStatus;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


/**
 * 定时任务
 */
@Configuration
@EnableScheduling
public class ScheduledTask {

    @Autowired
    private YbService ybService;

    // 定时易宝分润转出
    @Scheduled(cron = "0 0 1 * * ?")
    public void transferToCustomer() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        Date beginTime = cal.getTime();
        // 查询日期
        String beginDate = new SimpleDateFormat("yyyy-MM-dd").format(beginTime) + " 00:00:00";
        String endDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + " 00:00:00";
        // 查询分润余额
        RestResponse restResponse = ybService.tradeInfo(beginDate,endDate);
        if (!restResponse.getCode().equals(String.valueOf(HttpStatus.SC_OK))){
            System.out.println("查询余额出错:"+restResponse.getMessage());
            return;
        }
        TradeInfoQueryResponse tradeInfoQueryResponse = (TradeInfoQueryResponse) restResponse.getResult();
        if (Double.valueOf(tradeInfoQueryResponse.getAmount()) <= 0){
            System.out.println("分润余额为0");
            return;
        }
        restResponse = ybService.transferToCustomer(tradeInfoQueryResponse.getAmount());
        if (!restResponse.getCode().equals(String.valueOf(HttpStatus.SC_OK))){
            System.out.println("分润余额转出出错:"+restResponse.getMessage());
            return;
        }else {
            System.out.println("分润余额转出成功");
            System.out.println(new Gson().toJson(restResponse.getResult()));
        }
    }

    @Test
    public void test(){
        transferToCustomer();
    }

}
